/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.sys.modular.course.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import vip.xiaonuo.core.context.login.LoginContextHolder;
import vip.xiaonuo.core.enums.CommonStatusEnum;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.exception.enums.StatusExceptionEnum;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.login.SysLoginUser;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.sys.core.enums.AdminTypeEnum;
import vip.xiaonuo.sys.modular.course.dto.CourseQryDto;
import vip.xiaonuo.sys.modular.course.entity.Course;
import vip.xiaonuo.sys.modular.course.entity.CourseLimit;
import vip.xiaonuo.sys.modular.course.enums.CourseExceptionEnum;
import vip.xiaonuo.sys.modular.course.mapper.CourseMapper;
import vip.xiaonuo.sys.modular.course.param.CourseParam;
import vip.xiaonuo.sys.modular.course.service.CourseLimitService;
import vip.xiaonuo.sys.modular.course.service.CourseService;
import vip.xiaonuo.sys.modular.course.vo.CourseVo;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 实验课程service接口实现类
 *
 * @author levin
 * @date 2022-07-08 10:59:16
 */
@Service
@Transactional
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Resource
    private CourseLimitService courseLimitService;


    @Override
    public PageResult<CourseVo> getPageList(CourseQryDto dto) {
        //当前登录用户
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        if (!sysLoginUser.getAdminType().equals(AdminTypeEnum.SUPER_ADMIN.getCode())) {
            dto.setCollId(sysLoginUser.getCollId());
        }
        return new PageResult<>(this.baseMapper.getPageList(PageFactory.defaultPage(), dto));
    }

    @Override
    public List<CourseVo> getList(CourseQryDto dto) {
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        if (!sysLoginUser.getAdminType().equals(AdminTypeEnum.SUPER_ADMIN.getCode())) {
            dto.setCollId(sysLoginUser.getCollId());
        }
        return this.baseMapper.getList(dto);
    }

    @Override
    public void add(CourseParam courseParam) {
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        if (CollectionUtils.isEmpty(courseParam.getLimitList())) {
            throw new ServiceException(CourseExceptionEnum.EMPTY_LIMIT);
        }
        if (getInfoByParam(courseParam.getName(), courseParam.getCollId(), null) != null) {
            throw new ServiceException(CourseExceptionEnum.REPEAT_NAME);
        }
        Course course = new Course();
        BeanUtil.copyProperties(courseParam, course);
        this.save(course);
        for (CourseLimit item : courseParam.getLimitList()) {
            if (item.getTagId() == null || item.getReqNum() == null) {
                throw new ServiceException(CourseExceptionEnum.EMPTY_LIMIT_CRY);
            }
            item.setCourseId(course.getId());
            item.setCreateTime(new Date());
            item.setCreateUser(sysLoginUser.getId());
            courseLimitService.save(item);
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<CourseParam> courseParamList) {
        courseParamList.forEach(courseParam -> {
            this.delById(courseParam.getId());
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(CourseParam courseParam) {
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        if (CollectionUtils.isEmpty(courseParam.getLimitList())) {
            throw new ServiceException(CourseExceptionEnum.EMPTY_LIMIT);
        }
        if (getInfoByParam(courseParam.getName(), courseParam.getCollId(), courseParam.getId()) != null) {
            throw new ServiceException(CourseExceptionEnum.REPEAT_NAME);
        }
        Course course = this.queryCourse(courseParam);
        BeanUtil.copyProperties(courseParam, course);
        this.updateById(course);
        //先清空
        courseLimitService.delByCourseId(courseParam.getId());
        for (CourseLimit item : courseParam.getLimitList()) {
            item.setCourseId(course.getId());
            item.setCreateTime(new Date());
            item.setCreateUser(sysLoginUser.getId());
            courseLimitService.save(item);
        }
    }

    @Override
    public CourseVo detail(CourseParam courseParam) {
        CourseVo result = new CourseVo();
        Course entity = this.queryCourse(courseParam);
        BeanUtil.copyProperties(entity, result);
        List<CourseLimit> limitList = courseLimitService.getListByCourseId(courseParam.getId());
        result.setLimitList(limitList);
        return result;
    }

    @Override
    public void changeStatus(CourseParam courseParam) {
        //当前登录用户
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        Long id = courseParam.getId();

        Integer status = courseParam.getStatus();
        //校验状态在不在枚举值里
        CommonStatusEnum.validateStatus(status);
        //更新枚举，更新只能更新未删除状态的
        LambdaUpdateWrapper<Course> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Course::getId, id)
                .and(i -> i.ne(Course::getStatus, CommonStatusEnum.DELETED.getCode()))
                .set(Course::getStatus, status).set(Course::getUpdateTime, new Date()).set(Course::getUpdateUser, sysLoginUser.getId());
        boolean update = this.update(updateWrapper);
        if (!update) {
            throw new ServiceException(StatusExceptionEnum.UPDATE_STATUS_ERROR);
        }
    }

//    @Override
//    public CourseVo detail(CourseParam courseParam) {
//        return this.queryCourse(courseParam);
//    }

    /**
     * 获取实验课程
     *
     * @author levin
     * @date 2022-07-08 10:59:16
     */
    private Course queryCourse(CourseParam courseParam) {
        Course course = this.getById(courseParam.getId());
        if (ObjectUtil.isNull(course)) {
            throw new ServiceException(CourseExceptionEnum.NOT_EXIST);
        }
        return course;
    }

    private int delById(Long id) {
        //当前登录用户
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        Course entity = new Course();
        entity.setId(id);
        entity.setStatus(2);
        entity.setUpdateTime(new Date());
        entity.setUpdateUser(sysLoginUser.getId());
        return this.updateById(entity) ? 1 : 0;
    }

    private Course getInfoByName(String name) {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(Course::getStatus, 0, 1);
        queryWrapper.lambda().eq(Course::getName, name);
        return this.getOne(queryWrapper);
    }

    private Course getInfoByParam(String name, Long collId, Long id) {
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(Course::getStatus, 0, 1);
        queryWrapper.lambda().eq(Course::getName, name);
        queryWrapper.lambda().eq(Course::getCollId, collId);
        if (id != null) {
            queryWrapper.lambda().ne(Course::getId, id);
        }
        return this.getOne(queryWrapper);
    }
}
